package com.abc.recycling.service.impl;

import com.abc.recycling.mapper.AddressMapper;
import com.abc.recycling.model.Address;
import com.abc.recycling.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;

    @Override
    public List<Address> getAddressList(Long userId) {
        return addressMapper.findByUserId(userId);
    }

    @Override
    public Address getAddress(Long userId, Long addressId) {
        return addressMapper.findByIdAndUserId(addressId, userId);
    }

    @Override
    @Transactional
    public Address addAddress(Long userId, Address address) {
        address.setUserId(userId);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        addressMapper.insert(address);
        return address;
    }

    @Override
    @Transactional
    public void updateAddress(Long userId, Address address) {
        address.setUserId(userId);
        address.setUpdateTime(LocalDateTime.now());
        int rows = addressMapper.update(address);
        if (rows == 0) {
            throw new RuntimeException("地址不存在或无权限修改");
        }
    }

    @Override
    @Transactional
    public void deleteAddress(Long userId, Long addressId) {
        int rows = addressMapper.deleteByIdAndUserId(addressId, userId);
        if (rows == 0) {
            throw new RuntimeException("地址不存在或无权限删除");
        }
    }
} 